<?php


namespace app\service;


use app\model\Result;
use think\facade\Db;

class LoveService
{

    /**
     * 查看用户是否收藏商品
     */
    public static function goodsLoveCheck($param) {

        $field = 'goods_uuid';

        $res = Db::name('love')->field($field)->where('goods_uuid',$param['goods_uuid'])->where('user_uuid',$param['user_uuid'])->where('status',1)->find();
        if (!empty($res)) {
            return 1;
        }
        else
        {
            return 0;
        }
    }

    /**
     * 收藏商品
     */
    public static function goodsLoveAdd($param) {

        $field = 'goods_uuid';

        $res = Db::name('love')->field($field)->where('goods_uuid',$param['goods_uuid'])->where('user_uuid',$param['user_uuid'])->find();
        if (!empty($res)) {
            return Result::index(100,'已收藏','');
        }

        Db::startTrans();
        try{
            $param['status'] = 1;
            Db::name('love')->insertGetId($param);

            $love_num = Db::name('love')->field($field)->where('goods_uuid',$param['goods_uuid'])->where('status',1)->count();
            Db::name('goods')->where('uuid',$param['goods_uuid'])->update([
                'love_num' => (int)$love_num
            ]);
            Db::commit();
            return Result::index(200,'收藏成功',$res);

        } catch (\Exception $e) {
            Db::rollback();
            return Result::index(100,'收藏失败',$e);
        }
    }

    /**
     * 取消收藏商品
     */
    public static function goodsLoveReduce($param) {

        $field = 'goods_uuid';

        $res = Db::name('love')->field($field)->where('goods_uuid',$param['goods_uuid'])->where('user_uuid',$param['user_uuid'])->where('status',1)->find();
        if (empty($res)) {
            return Result::index(100,'未收藏该商品','');
        }

        Db::startTrans();
        try{
            $res = Db::name('love')->where('goods_uuid','=',$param['goods_uuid'])->where('user_uuid','=',$param['user_uuid'])->delete();

            $love_num = Db::name('love')->field($field)->where('goods_uuid',$param['goods_uuid'])->where('status',1)->count();
            Db::name('goods')->where('uuid',$param['goods_uuid'])->update([
                'love_num' => (int)$love_num
            ]);
            Db::commit();
            return Result::index(200,'取消收藏成功',$res);

        } catch (\Exception $e) {
            Db::rollback();
            return Result::index(100,'取消收藏失败',$e);
        }
    }

    /**
     * 返回用户收藏商品列表
     */
    public static function goodsLoveList($param) {

        $field = 'goods_uuid';

        $res = Db::name('love')->field($field)->where('user_uuid',$param['user_uuid'])
            ->alias("a")
            ->join('goods b', 'a.goods_uuid = b.uuid')
            ->field('b.*')
            ->limit($param['startPage'],$param['endPage'])->select();

        return Result::index(200,'返回成功',$res);

    }
}
